//
//  cooperateRecodeViewController.m
//  EasyToTesco2.0
//
//  Created by 袖手旁觀 on 16/6/24.
//  Copyright © 2016年 EasyToTesco. All rights reserved.
//

#import "cooperateRecodeViewController.h"
#import "shopselectView.h"
#import "cooperateRecodeTableViewCell.h"
#import "cooperateModel.h"

@interface cooperateRecodeViewController () <ShopSelectViewDelegate,UITableViewDataSource,UITableViewDelegate,UIAlertViewDelegate>
{
    
    NSInteger _orderstate;
    NSString *typeNumber;
    
    // 记录点击当前行
    NSInteger indexPathForRow;
    
    // 判断cell是否可点击
    BOOL isUpDataCell;
    
    MBProgressHUD *progressHUD;
    
    // 点击判断
    BOOL oilBtnState;
    BOOL wholeBtonState;
    BOOL firstDidClickOilButton;
    
    // 上拉数值
    NSInteger _refreshWhole;
    NSInteger _refreshOilorder;

}

@property (nonatomic,strong)UITableView *cashTableView;

@property (nonatomic,strong)shopselectView *select;

/**
 *  现金
 */
@property (nonatomic,strong)NSMutableArray *cashArray;

/**
 *  积分
 */
@property (nonatomic,strong)NSMutableArray *pointArray;

/**
 *  临时接收数组
 */
@property (nonatomic,strong)NSMutableArray *tempMutableArray;


@end

/**
 *  现金
 */
static NSString *const CashReuseIdentifier = @"Cash";

/**
 *  积分
 */
static NSString *const PointreuseIdentifier = @"Point";
@implementation cooperateRecodeViewController

- (NSMutableArray *)tempMutableArray {
    if (!_tempMutableArray) {
        _tempMutableArray = [NSMutableArray array];
    }
    return _tempMutableArray;
}

- (NSMutableArray *)cashArray {
 
    if (!_cashArray) {
        _cashArray = [NSMutableArray array];
    }
    return _cashArray;
}

- (NSMutableArray *)pointArray {
    if (!_pointArray) {
        _pointArray = [NSMutableArray array];
    }
    return _pointArray;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    progressHUD = [MBProgressHUD loadingInformationToView];
    [self.view addSubview:progressHUD];
    [self.navigationController setNavigationBarHidden:NO animated:YES];
    self.select.userInteractionEnabled = NO;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"合作记录";
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    typeNumber = @"1";
    _refreshWhole = 1;
    _refreshOilorder = 1;
    firstDidClickOilButton = YES;
    isUpDataCell = NO;
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    [self addHeaderTwoOrderUI];
    
    [self addTableView];
    
    [self addPullUpdateData];
    
    [self MyOrderGethoilDataSources];
}

#pragma mark ----- 数据加载
/**
 *  刷新当前行
 *
 *  @param param 传入当前行字典
 */
- (void)upDataDidClickCell :(NSDictionary *)param andButtonIndex:(NSInteger)buttonInteger {
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:param AndMenthodName:@"/api/Hz/Clhz" completeBlock:^(id object) {
        NSLog(@"%@",object);
        
            }];
}

/**
 *  成功
 */
- (void)didClickCellSuccessAndUpDataCell:(NSString *)SuccessIdString {
    
    NSDictionary *params = @{
                             @"id":SuccessIdString,
                             @"uname":USERNAME
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cooperation/newPass" completeBlock:^(id object) {
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"操作成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                
                NSString *value = @"1";
                
                if (_orderstate == 1000) {
                    [self.cashArray[indexPathForRow] setValue:value forKey:@"zt"];
                } else {
                    [self.pointArray[indexPathForRow] setValue:value forKey:@"zt"];
                }
                
                isUpDataCell = YES;
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:indexPathForRow inSection:0];
                [self.cashTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
            }];
            
            [self.view addSubview:hud];
        } else {
            
            NSDictionary *message = [object objectForKey:@"message"];
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:message[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        }
        
    }];
}

- (void)didClickCellFaildAndUpDataCell:(NSString *)SuccessIdString {
    
    NSDictionary *params = @{
                             @"id":SuccessIdString,
                             @"uname":USERNAME
                             };
    
    [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cooperation/newNotpass" completeBlock:^(id object) {
        NSLog(@"%@",object);
        if (JudgeBackDataCode) {
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:@"操作成功" toView:self.view dimBackground:NO AndCompleteBlock:^(id object) {
                
                NSString *value = @"2";
                
                if (_orderstate == 1000) {
                    [self.cashArray[indexPathForRow] setValue:value forKey:@"zt"];
                } else {
                    [self.pointArray[indexPathForRow] setValue:value forKey:@"zt"];
                }
                
                isUpDataCell = YES;
                
                NSIndexPath *indexPath = [NSIndexPath indexPathForRow:indexPathForRow inSection:0];
                [self.cashTableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath,nil] withRowAnimation:UITableViewRowAnimationRight];
            }];
            
            [self.view addSubview:hud];
        } else {
            
            NSDictionary *message = [object objectForKey:@"message"];
            
            MBProgressHUD *hud = [MBProgressHUD showMessage:message[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
            [self.view addSubview:hud];
        }
        
    }];
}

/**
 *  现金 -- 1
 */
- (void)MyOrderGethoilDataSources {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *params = @{
                                 @"uname":USERNAME,
                                 @"pay_type":typeNumber,
                                 @"p":[NSString stringWithFormat:@"%ld",_refreshOilorder],
                                 };
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"/api/Cooperation/newLists" completeBlock:^(id object) {
            
//            NSLog(@"%@",object);
            
            if (JudgeBackDataCode) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hide:YES];
                    self.select.userInteractionEnabled = YES;
                });
                
                NSDictionary *dictionary = [object objectForKey:@"data"];
                NSArray *arr = dictionary[@"list"];
//                NSLog(@"%@",arr);
                
                for (NSDictionary *dict in arr) {
                    cooperateModel *cooperate = [[cooperateModel alloc] initWithDictionary:dict error:nil];
                    if (cooperate) {
                        [self.tempMutableArray addObject:cooperate];
                    }
                }
                
                if (self.tempMutableArray.count == 0) {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        MBProgressHUD *hud = [MBProgressHUD showMessage:@"暂无更多数据" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                        [self.view addSubview:hud];
                        
                        [self.cashTableView.mj_footer endRefreshingWithNoMoreData];
                    });
                    
                    return;
                }
                
                for (cooperateModel *cooperate in self.tempMutableArray) {
                    [self.cashArray addObject:cooperate];
                }
                
                [self.tempMutableArray removeAllObjects];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.cashTableView reloadData];
                });

            } else {
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hide:YES];
                    self.select.userInteractionEnabled = YES;
                    [self.cashTableView.mj_footer endRefreshingWithNoMoreData];
                });
                
                NSDictionary *dict = [object objectForKey:@"message"];
                
                MBProgressHUD *hud = [MBProgressHUD showMessage:dict[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
            }
        }];

    });
}

/**
 *  积分 -- 2
 */
- (void)MyOrderDataSources {
    
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSDictionary *params = @{
                                 @"uname":USERNAME,
                                 @"pay_type":typeNumber,
                                 @"p":[NSString stringWithFormat:@"%ld",_refreshWhole],
                                 };
        
        [[NetWorkSharedTools sharedNetWorkTools] objectWithURLDict:params AndMenthodName:@"api/Cooperation/newLists" completeBlock:^(id object) {
            
            if (JudgeBackDataCode) {
             
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hide:YES];
                    self.select.userInteractionEnabled = YES;
                });
                
                NSDictionary *dictionary = [object objectForKey:@"data"];
                NSArray *arr = dictionary[@"list"];
                
                for (NSDictionary *dict in arr) {
                    cooperateModel *cooperate = [[cooperateModel alloc] initWithDictionary:dict error:nil];
                    if (cooperate) {
                        [self.tempMutableArray addObject:cooperate];
                    }
                }
                
                if (self.tempMutableArray.count == 0) {
                    
                    dispatch_async(dispatch_get_main_queue(), ^{
                        MBProgressHUD *hud = [MBProgressHUD showMessage:@"暂无更多数据" toView:self.view dimBackground:NO AndCompleteBlock:nil];
                        [self.view addSubview:hud];
                        
                        [self.cashTableView.mj_footer endRefreshingWithNoMoreData];
                    });
                    
                    return;
                }
                
                for (cooperateModel *cooperate in self.tempMutableArray) {
                    [self.pointArray addObject:cooperate];
                }
                
                [self.tempMutableArray removeAllObjects];
                
                dispatch_async(dispatch_get_main_queue(), ^{
                    [self.cashTableView reloadData];
                });
                
            } else {
             
                dispatch_async(dispatch_get_main_queue(), ^{
                    [progressHUD hide:YES];
                    self.select.userInteractionEnabled = YES;
                    [self.cashTableView.mj_footer endRefreshingWithNoMoreData];
                });
                
                NSDictionary *dict = [object objectForKey:@"message"];
                
                MBProgressHUD *hud = [MBProgressHUD showMessage:dict[@"view"] toView:self.view dimBackground:NO AndCompleteBlock:nil];
                [self.view addSubview:hud];
                
            }
            
        }];

    });
}

#pragma mark ----- 添加子控件
- (void)addTableView {
    CGFloat y = CGRectGetMaxY(self.select.frame);
//    NSLog(@"%f",y);
    self.cashTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, y, WIDTH, HEIGHT - y - 20 - HEIGHT * 0.07)style:UITableViewStylePlain];
    self.cashTableView.delegate = self;
    self.cashTableView.dataSource = self;
    self.cashTableView.backgroundColor = BACKGROUND_COLOR;
    self.cashTableView.tableFooterView = [[UIView alloc] init];
    self.cashTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:self.cashTableView];
    
    _orderstate = 1000;
}

- (void)addHeaderTwoOrderUI {
//    shopselectView *select = [[shopselectView alloc] initWithFrame:CGRectMake(0, HEIGHT * 0.1, WIDTH, HEIGHT * 0.07)];
    
    shopselectView *select = [[shopselectView alloc] initWithFrame:CGRectMake(0,0, WIDTH, HEIGHT * 0.07)];
    
    select.delegate = self;
    
    self.select = select;
    
    [self.view addSubview:select];
}


#pragma mark ----- UITableViewDelegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    NSLog(@"%ld",indexPath.row);
    
    if (_orderstate == 1000) {
        cooperateModel *model = self.cashArray[indexPath.row];
        if (![model.zt isEqualToString:@"0"]) {
            return;
        }
        indexPathForRow = indexPath.row;
        [self judgePersonChoose];
        
    } else {
        cooperateModel *model = self.pointArray[indexPath.row];
        if (![model.zt isEqualToString:@"0"]) {
            return;
        }
        indexPathForRow = indexPath.row;
        [self judgePersonChoose];
        
        NSLog(@"jifen");
    }
}

#pragma mark ----- 点击方法
- (void)selectBtnClick:(UIButton *)button {
    _orderstate = button.tag;
    
    [self.cashTableView.mj_footer resetNoMoreData];
    //现金
    if (button.tag == 1000) {
        NSLog(@"现金");
        if (firstDidClickOilButton) {
            firstDidClickOilButton = NO;
            return;
        }
//
//        if (oilBtnState == YES) {
//            _refreshOilorder ++;
//        }
        if(oilBtnState) {
            return;
        }
        
        if (!button.selected && _refreshOilorder == 1) {
            progressHUD = [MBProgressHUD loadingInformationToView];
            [self.view addSubview:progressHUD];
            self.select.userInteractionEnabled = NO;
        }
        
        typeNumber = @"1";

        [self.pointArray removeAllObjects];
        [self.cashTableView reloadData];
        [self MyOrderGethoilDataSources];
        
        wholeBtonState = NO;
        oilBtnState = YES;
        _refreshWhole = 1;
    } else if(button.tag == 1001){
        //积分
        NSLog(@"积分");
//        if (wholeBtonState == YES) {
//            _refreshWhole ++;
//        }
        if (wholeBtonState) {
            return;
        }
        
        if (!button.selected && _refreshWhole == 1) {
            progressHUD = [MBProgressHUD loadingInformationToView];
            [self.view addSubview:progressHUD];
            self.select.userInteractionEnabled = NO;
        }
        
        typeNumber = @"2";
        [self.cashArray removeAllObjects];
        [self.cashTableView reloadData];
        [self MyOrderDataSources];
        
        wholeBtonState = YES;
        oilBtnState = NO;
        _refreshOilorder = 1;
        firstDidClickOilButton = NO;
    }else {
        NSLog(@"%s",__func__);
    }
}

#pragma mark ----- 上拉刷新
- (void)addPullUpdateData
{
    self.cashTableView.mj_footer = [TopPullRefreshAnaimation footerWithRefreshingTarget:self refreshingAction:@selector(BusinessDetailsLoadMoreData)];
    
}

- (void)BusinessDetailsLoadMoreData
{
    
    if (_orderstate == 1000) {
        NSLog(@"现金");
        _refreshOilorder ++;
        [self MyOrderGethoilDataSources];
    } else {
        NSLog(@"积分");
        _refreshWhole ++;
        [self MyOrderDataSources];
    }
    
    [self.cashTableView.mj_footer endRefreshing];
}

#pragma mark ----- 点击操作逻辑

- (void)judgePersonChoose {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您正在进行交易操作,请确认下一步交易选择" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    
    alert.tag = 100101;
    
    [alert show];
}

- (void)didCellClickChooseSuccessAndDefault {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:@"您正在进行交易操作,请选择允许或不允许" delegate:self cancelButtonTitle:@"允许" otherButtonTitles:@"不允许", nil];
    
    alert.tag = 100102;
    
    [alert show];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
    if (alertView.tag == 100101) {
        if (buttonIndex == 0) {
            [self didCellClickChooseSuccessAndDefault];
        }
    }
    
    if (alertView.tag == 100102) {
        
        cooperateModel *model;
        
        if (_orderstate == 1000) {
            model = self.cashArray[indexPathForRow];
        } else {
            model = self.pointArray[indexPathForRow];
        }
        
        NSLog(@"%@",model);
        
        if (buttonIndex == 0) {
            NSLog(@"允许");
            [self didClickCellSuccessAndUpDataCell:model.replaceID];
        } else {
            NSLog(@"不允许");
            [self didClickCellFaildAndUpDataCell:model.replaceID];
        }
//        buttonIndex ++;
//        NSLog(@"%ld",buttonIndex);
//        NSDictionary *param = @{
//                                @"id":model.replaceID,
//                                @"clfs":@(buttonIndex)
//                                };
//        NSLog(@"%@",param);
//        [self upDataDidClickCell:param andButtonIndex:buttonIndex];
    }
}

#pragma mark ----- UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_orderstate == 1000) {
        return self.cashArray.count;
    } else {
        return self.pointArray.count;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (_orderstate == 1000) {
        
        cooperateRecodeTableViewCell *cashCell = [tableView dequeueReusableCellWithIdentifier:CashReuseIdentifier];
        
        if (!cashCell) {
            cashCell = [[cooperateRecodeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CashReuseIdentifier];
            cashCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cooperateModel *cooperate = self.cashArray[indexPath.row];
        cashCell.cooperate = cooperate;
        
//        if (isUpDataCell) {
//            isUpDataCell = NO;
//            if (indexPathForRow == 1) {
//                cashCell.headerLabel.text = @"交易成功";
//            }
//            
//            if (indexPathForRow == 2) {
//                cashCell.headerLabel.text = @"交易失败";
//            }
//        }
        cashCell.topUpMoney.text = [NSString stringWithFormat:@"积分权:%@",cooperate.jine];
        
        return cashCell;
    } else {
        
        cooperateRecodeTableViewCell *pointCell = [tableView dequeueReusableCellWithIdentifier:PointreuseIdentifier];
        
        if (!pointCell) {
            pointCell = [[cooperateRecodeTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:PointreuseIdentifier];
            pointCell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        cooperateModel *cooperate = self.pointArray[indexPath.row];
        pointCell.cooperate = cooperate;
        
//        if (isUpDataCell) {
//            isUpDataCell = NO;
//            if (indexPathForRow == 1) {
//                pointCell.headerLabel.text = @"交易成功";
//            }
//            
//            if (indexPathForRow == 2) {
//                pointCell.headerLabel.text = @"交易失败";
//            }
//        }
        pointCell.topUpMoney.text = [NSString stringWithFormat:@"代金券:%@",cooperate.jine];
                
        return pointCell;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 140;
}


@end
